package com.offcn.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.offcn.pojo.Permission;
import com.offcn.pojo.Role;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wy
 * @Date: 2022/9/7 09:32
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        com.offcn.pojo.User loginUser = userService.getOneUserByName(username);


        List<GrantedAuthority> auth = new ArrayList<>();

        //判断用户名是否正确
        if (loginUser == null) {
            throw new UsernameNotFoundException("用户名不存在!");
        }

        //给用户设置角色信息
        List<Role> roleInfoByUid = userService.getRoleInfoByUid(loginUser.getId());
        if (roleInfoByUid != null && roleInfoByUid.size() > 0) {
            System.out.println("=================角色=================");
            for (Role role : roleInfoByUid) {
                SimpleGrantedAuthority simpleGrantedAuthority01
                        = new SimpleGrantedAuthority(role.getKeyword());
                auth.add(simpleGrantedAuthority01);
                System.out.println(role.getKeyword());
            }
        }
        //配置角色 权限
        List<Permission> permissionByUid = userService.getPermissionByUid(loginUser.getId());
        if (permissionByUid != null && permissionByUid.size() > 0) {
            System.out.println("=================权限=================");
            for (Permission permission : permissionByUid) {
                SimpleGrantedAuthority simpleGrantedAuthority02
                        = new SimpleGrantedAuthority(permission.getKeyword());
                auth.add(simpleGrantedAuthority02);
                System.out.println(permission.getKeyword());
            }
        }

        return new User(username, loginUser.getPassword(), auth);
    }
}
